package anfangcron

import (
	"time"
	"fmt"
	"sync"
	"strings"
	"github.com/astaxie/beego/httplib"
	"strconv"
	"log"
)

var DianCiDataMu sync.Mutex
var GPS []float64 = []float64{0, 0}
var Wendu string = ""
var Shidu string = ""
var DianChang string = ""
var CiChang string = ""
var DianChi string = ""
var GPS_str []string = []string{"", ""}
var flag_GPS bool = false

func StartCheckPostData() {
	time.Sleep(time.Second * 30)
	ticker := time.NewTicker(time.Second * 10)
	for _ = range ticker.C {
		fmt.Println("post check! every ten second")
		PostData()
	}
}

func SaveData(data string) {
	defer func() {
		if e := recover(); e != nil {
			log.Println("[channel closed]", e)
		}
	}()
	DianCiDataMu.Lock()
	defer DianCiDataMu.Unlock()
	if strings.Index(data, "BAT") != -1 {
		if strings.Index(data, "*") == -1 {
			return
		}
		DianChi = data[strings.Index(data, "=")+1:strings.Index(data, "*")]
	}
	if strings.Index(data, "TMP") != -1 {
		if strings.Index(data, "*") == -1 {
			return
		}
		Wendu = data[strings.Index(data, "=")+1:strings.Index(data, ",") ]
		Shidu = data[strings.Index(data, ",")+1:strings.Index(data, "*")]
	}
	if strings.Index(data, "GPRMC") != -1 {
		flag_GPS = true
		tmp := strings.Split(data, ",")
		if len(tmp) < 12 {
			return
		}
		var err error
		GPS_str[0] = tmp[3]
		GPS_str[1] = tmp[5]
		if GPS[0], err = strconv.ParseFloat(tmp[3], 32); err != nil {
			return
		}
		if GPS[1], err = strconv.ParseFloat(tmp[5], 32); err != nil {
			return
		}
		GPS[0] = GPS[0] / 100
		GPS[1] = GPS[1] / 100
	} else if strings.Index(data, "GPGLL") != -1 {
		flag_GPS = true
		tmp := strings.Split(data, ",")
		if len(tmp) < 8 {
			return
		}
		GPS_str[0] = tmp[1]
		GPS_str[1] = tmp[3]
		var err error
		if GPS[0], err = strconv.ParseFloat(tmp[1], 32); err != nil {
			return
		}
		if GPS[1], err = strconv.ParseFloat(tmp[3], 32); err != nil {
			return
		}
		GPS[0] = GPS[0] / 100
		GPS[1] = GPS[1] / 100
	}
	if strings.Index(data, "MES") != -1 {
		if strings.Index(data, "*") == -1 {
			return
		}
		if strings.Index(data, "uT") != -1 {
			DianChang = data[strings.Index(data, "=")+1:strings.Index(data, ";") ]
			CiChang = data[strings.Index(data, ";")+1:strings.Index(data, "; V/m")]
		} else {
			DianChang = data[strings.Index(data, "=")+1:strings.Index(data, ";") ]
		}
	}
}

func PostData() {
	DianCiDataMu.Lock()
	defer DianCiDataMu.Unlock()
	if !flag_GPS || (Wendu == "" && Shidu == "") || (DianChang == "" && CiChang == "") || DianChi == "" {
		return
	} else {
		//go PostToLaoyu(CiChang, DianChang, DianChi, strconv.FormatFloat(GPS[0], 'f', 6, 32), strconv.FormatFloat(GPS[1], 'f', 6, 32), Wendu, Shidu)
		go PostToLaoyu_new(CiChang, DianChang, DianChi, strconv.FormatFloat(GPS[0], 'f', 6, 32), strconv.FormatFloat(GPS[1], 'f', 6, 32), Wendu, Shidu)
		GPS[0] = float64(0);
		GPS[1] = float64(0);
		Wendu = "";
		Shidu = "";
		DianChang = "";
		CiChang = "";
		DianChi = "";
		GPS_str[0] = "";
		GPS_str[1] = ""
		flag_GPS = false
		return
	}
	return
}

//func PostToLaoyu(CiChang1 string, DianChang1 string, DianLiang1 string, GPS1 []string, WenDu1 string, ShiDu1 string) {
//	fmt.Printf("GPS(lng:%slat:%s),WenDu:%s,ShiDu:%s,DianChang:%s,CiChang:%s,DianChi:%s\r\n", GPS1[0], GPS1[1], WenDu1, ShiDu1, DianChang1, CiChang1, DianLiang1)
//	log.Printf("GPS(lng:%slat:%s),WenDu:%s,ShiDu:%s,DianChang:%s,CiChang:%s,DianChi:%s\r\n", GPS1[0], GPS1[1], WenDu1, ShiDu1, DianChang1, CiChang1, DianLiang1)
//}

func PostToLaoyu(CiChang1 string, DianChang1 string, DianLiang1 string, lat string, lng string, WenDu1 string, ShiDu1 string) {
	req := httplib.Post("http://45.32.113.2:1024/d/send/1")

	req.Param("data[0][magnetic]", CiChang1)
	req.Param("data[0][electric]", DianChang1)
	req.Param("data[0][battery]", DianLiang1)
	req.Param("data[0][humidity]", WenDu1)
	req.Param("data[0][temperature]", ShiDu1)
	req.Param("data[0][lat]", lat)
	req.Param("data[0][lng]", lng)
	req.Param("data[0][dataTime]", strconv.FormatInt(time.Now().Unix(), 10))

	req.Header("Content-Type", "application/x-www-form-urlencoded")

	str, err := req.Debug(true).String()
	log.Println(str, err)
}

func PostToLaoyu_new(CiChang1 string, DianChang1 string, DianLiang1 string, lat string, lng string, WenDu1 string, ShiDu1 string) {
	log.Println("logged to other server!")
	req := httplib.Post("http://www.nucurie.com:1024/d/send/1")

	req.Param("data[0][magnetic]", CiChang1)
	req.Param("data[0][electric]", DianChang1)
	req.Param("data[0][battery]", DianLiang1)
	req.Param("data[0][humidity]", WenDu1)
	req.Param("data[0][temperature]", ShiDu1)
	req.Param("data[0][lat]", lat)
	req.Param("data[0][lng]", lng)
	req.Param("data[0][dataTime]", strconv.FormatInt(time.Now().Unix(), 10))

	req.Header("Content-Type", "application/x-www-form-urlencoded")

	str, err := req.Debug(true).String()
	log.Println(str, err)
}
